# coding:utf-8

from sqlalchemy import event

from .models import Partic, UserInfo
from .constant import ParticStatus
from common.constant import FREE_REASON_COUNTER_KEY
from common.utils import redis_client


@event.listens_for(Partic.status, 'set', active_history=True)
def sync_free_reason_cnt(target, value, oldvalue, initiator):
    """
    created by chenhj at 2018/4/2
    当成单20次, 则增加一次无理由退款次数, 并重置计数器
    """
    if value != oldvalue and value == ParticStatus.SUCCEED.value:
        if not target.is_robot and not target.is_training:
            key = FREE_REASON_COUNTER_KEY.format(user_id=target.supplier_id)
            user_info = UserInfo.default_user_info(target.supplier_id)
            counter = redis_client.incr(key)
            if counter >= 20:
                user_info.free_reason_feedback_cnt += 1
                redis_client.delete(key)
